<template>
  <div class="content-wrap home-wrap">
    <div class="content-wrap">
      <Card>
        <div slot="title">
          <Select
            v-model="selectPage"
            placeholder="页面选择"
            style="width: 200px;margin-right:10px;"
            @on-change="handleSelectPage"
          >
            <Option v-for="item of tplList" :key="item.id" :value="item.id">{{ item.templateName }}</Option>
          </Select>
          <Tooltip content="全屏" placement="top" transfer>
            <Button type="success" shape="circle" icon="md-contract" title="全屏" @click.prevent="fullScreenHandle" />
          </Tooltip>
        </div>
        <div class="page-view-wrap" ref="pageWrap" id="pageWrap" :class="{ 'full-screen': hasFullScreen }">
          <grid-layout
            :layout.sync="showList"
            :col-num="colNum"
            :max-rows="2"
            :row-height="rowHeight"
            :is-draggable="false"
            :is-resizable="false"
            :is-mirrored="false"
            :vertical-compact="false"
            :margin="[10, 10]"
            :use-css-transforms="false"
            :prevent-collision="false"
          >
            <grid-item
              v-for="item in showList"
              :x="item.x"
              :y="item.y"
              :w="item.w"
              :h="item.h"
              :i="item.i"
              :key="item.i"
            >
              <Card>
                <div slot="title">{{ item.title }}</div>
                <div class="chart-box">
                  <chart-comp
                    v-if="getChartData(item.key)"
                    :id="item.key"
                    :type="item.type"
                    :chartData="getChartData(item.key)"
                    :defaultOptions="getChartOptions(item.key)"
                  />
                  <Spin fix v-show="getLoading(item.key)">加载中...</Spin>
                </div>
              </Card>
            </grid-item>
          </grid-layout>
        </div>
      </Card>
    </div>
  </div>
</template>
<script>
import { find, each, isEmpty } from 'lodash'
import VueGridLayout from 'vue-grid-layout'
import { fetchPageTplList, fetchPageData, fetchPageList } from '@/api/home'
import ChartComp from './components/ChartComp'
import chartOptionList from './chartOptionList'
import chartKeyList from './chartKeyList'
import modifyData from './modifyData'
const elementResizeDetectorMaker = require('element-resize-detector')

export default {
  name: 'Home',
  components: {
    GridLayout: VueGridLayout.GridLayout,
    GridItem: VueGridLayout.GridItem,
    ChartComp
  },
  data() {
    return {
      rowHeight: 0,
      colNum: 4,
      tplList: [],
      showList: [],
      selectPage: undefined,
      pageObj: {},
      chartDataObj: {},
      loadingObj: {},
      hasFullScreen: false
    }
  },
  beforeDestroy() {
    this.unListenerEsc()
  },
  deactivated() {
    this.unListenerEsc()
  },
  async activated() {
    await this.loadPageList()
    this.loadingPageTplList()
  },
  mounted() {
    this.dragDomResize()
  },
  methods: {
    setRowHeight() {
      const _wrapRle = this.$refs['pageWrap']
      const _wH = _wrapRle.offsetHeight
      this.rowHeight = (_wH - 30) / 2
    },
    dragDomResize() {
      const that = this
      const erd = elementResizeDetectorMaker()
      erd.listenTo(document.getElementById('pageWrap'), function(element) {
        that.$nextTick(function() {
          this.setRowHeight()
        })
      })
    },
    getLoading(key) {
      return this.loadingObj[key] ? this.loadingObj[key] : false
    },
    getChartData(key) {
      return this.chartDataObj[key] ? this.chartDataObj[key].data : null
    },
    getChartOptions(key) {
      return this.chartDataObj[key] ? this.chartDataObj[key].options : {}
    },
    async loadingPageTplList() {
      const { code, date } = await fetchPageTplList()
      if (code === 200) {
        const _hData = find(date, { isDefault: 1 })
        const _oldData = find(this.tplList, { isDefault: 1 })
        // 检测主页是否被修改，如果修改则重新处理数据，否则使用以前的
        if (!_oldData || (_hData && (_hData.id !== _oldData.id || _hData.context !== _oldData.context)) || isEmpty(this.chartDataObj)) {
          try {
            this.tplList = date
            const _cData = JSON.parse(_hData.context)
            this.showList = _cData
            this.selectPage = _hData.id
            this.$nextTick(() => {
              this.fetchChartData(_cData)
            })
          } catch (error) {
            this.showList = []
          }
        }
      } else {
        this.tplList = []
      }
    },
    fetchChartData(data) {
      each(data, item => {
        const { type, key, modeId } = item
        const _obj = find(this.pageObj[type].value, { modeId: Number(modeId) })
        if (_obj && _obj.value) {
          const { value } = _obj
          this.loadPageData(value, type, key, modeId)
        }
      })
    },
    async loadPageData(url, type, key, mId) {
      const _oData = find(chartOptionList, { modelId: Number(mId) })
      if (_oData) {
        const { options } = _oData
        this.$set(this.loadingObj, [key], true)
        this.$set(this.chartDataObj, [key], null)
        const { code, date } = await fetchPageData({
          url
        })
        this.loadingObj[key] = false
        if (code === 200) {
          const _cData = modifyData[`${type}${mId}`](date, options)
          this.chartDataObj[key] = {
            options,
            data: _cData
          }
        }
      }
    },
    async loadPageList() {
      const { code, date } = await fetchPageList()
      if (code === 200) {
        this.modifyPageList(date)
      }
    },
    modifyPageList(list) {
      const _obj = {}
      each(list, item => {
        const { modeName, modeUrl, modeId, modeType } = item
        const _data = find(chartKeyList, { value: Number(modeType) })
        if (_data) {
          const { label } = _data
          if (!_obj[label]) {
            _obj[label] = {
              name: label,
              value: []
            }
          }
          _obj[label].value.push({
            label: modeName,
            value: modeUrl,
            modeId
          })
        }
        this.pageObj = _obj
      })
    },
    handleSelectPage(val) {
      const _hData = find(this.tplList, { id: val })
      if (_hData) {
        try {
          const _cData = JSON.parse(_hData.context)
          this.showList = _cData
          this.selectPage = _hData.id
          this.fetchChartData(_cData)
        } catch (error) {
          this.showList = []
        }
      }
    },
    fullScreenHandle() {
      this.hasFullScreen = true
      this.listenerEsc()
    },
    listenerEsc() {
      document.addEventListener('keyup', this.escKeyHandle)
    },
    unListenerEsc() {
      document.removeEventListener('keyup', this.escKeyHandle)
    },
    escKeyHandle(event) {
      if (Number(event.keyCode) === 27) {
        this.hasFullScreen = false
        this.unListenerEsc()
      }
    }
  }
}
</script>
<style lang="less" scoped>
@deep: ~'>>>';

.content-wrap {
  padding: 10px;

  @{deep} .ivu-card-body {
    width: 100%;
    height: 100%;
    overflow: hidden;
  }

  .page-view-wrap {
    width: 100%;
    height: 100%;
  }

  .chart-box {
    width: 100%;
    height: 100%;
  }
  .full-screen {
    position: fixed !important;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 9999;
  }
}
</style>
